#include <QMessageBox>
#include "molecularvolume.h"
#include "../../datamanager/datanode.h"
#include "../../datamanager/datamanager.h"
#include "../../datamanager/proteindatanode.h"
#include "../../renderer/rendermanager.h"
#include "../../mainwindow.h"
#include "molvolumecontrol.h"

using namespace PBVP;

MolVolumePlugin::MolVolumePlugin()
{
	m_pControl = new MolVolumeControl(this);
	m_pBlurMap = new BlurMap();
}

MolVolumePlugin::~MolVolumePlugin()
{
	delete m_pBlurMap;
	delete m_pControl;
}

void MolVolumePlugin::initialize(MainInterface* mainInterface)
{
	Plugin::initialize(mainInterface);
	m_pDataManager = m_pMainInterface->getDataManager();
	m_pRenderManager = m_pMainInterface->getRenderManager();
	molVolAction = new QAction(tr("Construct Protein Volume"), m_pMainInterface->getMainWindow());
	molVolAction->setStatusTip(description());
	connect(molVolAction, SIGNAL(triggered()), this, SLOT(shownControl()));
	// errorMessage = new QErrorMessage(m_pMainInterface->getMainWindow());
}
bool MolVolumePlugin::isSupported(DataNode* pNode)
{
#ifdef __GNU__
	if(pNode->data()->getDataSetType() == PROTEIN_DATA) return true;
#else
	ProteinDataNode *pProteinNode = dynamic_cast<ProteinDataNode *>(pNode);
	if (pProteinNode)
	{
		return true;
	}
#endif
	return false;
}

//////////////////////////////////////////////////////////////////////////
// Public slots
//////////////////////////////////////////////////////////////////////////
void MolVolumePlugin::shownControl()
{
	DataNode *pNode = m_pDataManager->getCurrentNode();
	if (!pNode)
	{
		//errorMessage->showMessage("No Data Selected in DataManager");
		//errorMessage->exec();
		QMessageBox::critical(m_pMainInterface->getMainWindow(), "Error", "No Data Selected in DataManager");
		return;
	}
	if(!isSupported(pNode)) {
		//errorMessage->showMessage("Only Protein Data can be used for constructing volume");
		//errorMessage->exec();
		QMessageBox::critical(m_pMainInterface->getMainWindow(), "Error", "Only Protein Data can be used to construct volume");
		return;
	}
	AxisAlignedBox bbox = pNode->boundingBox();
	m_pBlurMap->setMinMaxExt(bbox.getMinimum(), bbox.getMaximum());
	m_pControl->init(m_pBlurMap);
	if (m_pControl->exec())
	{
		m_pControl->updateBlurMap(m_pBlurMap);
		ProteinData *pProtein = (ProteinData *)(pNode->data());
		Reg3DVolumeData *pReg3Data = m_pBlurMap->constructVolume(pProtein->getAtoms());
		Reg3DVolumeDataNode *pReg3Node = new Reg3DVolumeDataNode(pReg3Data, m_pMainInterface);
		pReg3Node->setName(pNode->getName().append("_density"));
		m_pRenderManager->setDefaultRenderer(pReg3Node);
		m_pDataManager->addDataNode(pReg3Node);
	}
}

Q_EXPORT_PLUGIN2(molvolume, MolVolumePlugin)
